//
//  SEGShareViewModel.m
//  SEGViewModel
//
//  Created by 山刘 on 2020/6/4.
//

#import "SEGShareViewModel.h"

#if __has_include(<WechatOpenSDK/WXApiObject.h>)
#import <WechatOpenSDK/WXApiObject.h>
#else
#import "WXApiObject.h"
#endif

#if __has_include(<WechatOpenSDK/WXApi.h>)
#import <WechatOpenSDK/WXApi.h>
#else
#import "WXApi.h"
#endif

#import <MessageUI/MessageUI.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterfaceObject.h>
#import <TencentOpenAPI/QQApiInterface.h>


@implementation SEGShareViewModel
#pragma mark - init
-(instancetype)init{
    if (self = [super init]) {
        [self racInit];
    }
    return self;
}
#pragma mark - business
- (void)racInit {}

-(void)checkWeChatEnvironment{
    
    if (kWeChatAppId.length == 0) {
        [self showMessage:@"暂未开通！"];
        return;
    }
    
    if (!WXApi.isWXAppInstalled) {
        [self showMessage:kWecharNotInstallTip];
        return;
    }
    if (!WXApi.isWXAppSupportApi) {
        [self showMessage:@"当前微信的版本不支持OpenApi！"];
        return;
    }
}

/// 微信分享、微信朋友圈分享
/// @param scene WXSceneSession、WXSceneTimeline
/// @param image 图片分享，高清图
/// @param thumbImage 网页分享，缩略图
/// @param title 网页分享，标题
/// @param description 网页分享，描述
/// @param webpageUrl 网页分享，URLString
/// @see seg_shareToWeChatWithIsWechat:
-(void)segShareToWeChatWithScene:(int)scene
                       ImageData:(UIImage*)image
                      ThumbImage:(UIImage*)thumbImage
                           Title:(NSString*)title
                     Description:(NSString*)description
                      WebpageUrl:(NSString*)webpageUrl{
    [self checkWeChatEnvironment];
    
    @try {
        WXMediaMessage *message = [WXMediaMessage message];
        
        if (image) { // 图片分享
            WXImageObject *imageObject = [WXImageObject object];
            imageObject.imageData = UIImagePNGRepresentation(image);
            message.mediaObject = imageObject;
        }else{ // 网页分享
            if (thumbImage) [message setThumbImage:thumbImage];//大小不能超过32K
            if(title) message.title = title;
            if(description) message.description = description;
            
            WXWebpageObject *ext = [WXWebpageObject object];
            if(webpageUrl) ext.webpageUrl = webpageUrl;
            message.mediaObject = ext;
        }
        
        SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
        req.bText = NO;
        req.message = message;
        req.scene = scene;
        
        [WXApi sendReq:req completion:nil];
    } @catch (NSException *exception) {
        [self showMessage:exception.description];
    }
}


/// 分享到小程序
/// @param params 参数
- (void)seg_shareToWeChatMiniProgramWithParams:(NSDictionary*)params{
    if (!params) return;
    
    [self checkWeChatEnvironment];
    
    @try {
        [[params allKeys] containsObject:@"webpageUrl"];
        WXMiniProgramObject *object = [WXMiniProgramObject object];
        object.webpageUrl = [[params allKeys] containsObject:@"webpageUrl"] ? [params valueForKey:@"webpageUrl"] : @"";
        object.userName = [[params allKeys] containsObject:@"userName"] ? [params valueForKey:@"userName"] : @"";
        object.path = [[params allKeys] containsObject:@"path"] ? [params valueForKey:@"path"] : @"";
        object.hdImageData = [[params allKeys] containsObject:@"hdImageData"] ? UIImageJPEGRepresentation((UIImage*)[params valueForKey:@"hdImageData"],0.5) : nil;
        if(![[[NSUserDefaults standardUserDefaults] valueForKey:kUserDefaultIsProduction] boolValue]){
            object.miniProgramType = WXMiniProgramTypePreview;
        }
        
        WXMediaMessage *message = [WXMediaMessage message];
        message.title = [[params allKeys] containsObject:@"title"] ? [params valueForKey:@"title"] : @"";
        message.description = [[params allKeys] containsObject:@"description"] ? [params valueForKey:@"description"] : @"";
        message.mediaObject = object;
        message.thumbData = nil;
        
        SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
        req.message = message;
        req.scene = WXSceneSession;  //目前只支持会话
        [WXApi sendReq:req completion:nil];
    } @catch (NSException *exception) {
        [self showMessage:exception.description];
    }
}

- (void)segShareToQQWithImageData:(UIImage*)image
                            Title:(NSString*)title
                 PreviewImageData:(UIImage*)previewImageData
                      Description:(NSString*)description
                       WebpageUrl:(NSString*)webpageUrl{
    
    if (![QQApiInterface isQQInstalled]) {
        [self showMessage:@"QQ未安装！"];
        return;
    }
    
    @try {
        SendMessageToQQReq *req;
        if (image) {//话题图片分享
            NSData * previewImageData = UIImagePNGRepresentation([UIImage imageWithContentsOfFile:SEGPicName(@"pic_default_70_70")]);
            QQApiImageObject *obj = [QQApiImageObject objectWithData:UIImagePNGRepresentation(image) previewImageData:previewImageData title:nil description:nil];
            req = [SendMessageToQQReq reqWithContent:obj];
        }else {
            NSURL *url = [NSURL URLWithString:webpageUrl];
            QQApiURLObject *obj = [QQApiURLObject objectWithURL:url title:title description:description previewImageData:UIImagePNGRepresentation(previewImageData) targetContentType:QQApiURLTargetTypeNews];
            req = [SendMessageToQQReq reqWithContent:obj];
        }
        
        //将内容分享到qq
        QQApiSendResultCode resultCode = [QQApiInterface sendReq:req];
        [self segShareToQQSendResult:resultCode];
    } @catch (NSException *exception) {
        [self showMessage:exception.description];
    }
}

//QQ分享接口调用结果 不是分享结果！！！
- (void)segShareToQQSendResult:(QQApiSendResultCode)sendResult
{
    NSString *errorMessage;
    switch (sendResult)
    {
        case EQQAPIAPPNOTREGISTED:
        {
            errorMessage = @"App未注册";
            break;
        }
        case EQQAPIMESSAGECONTENTINVALID:
        case EQQAPIMESSAGECONTENTNULL:
        case EQQAPIMESSAGETYPEINVALID:
        {
            errorMessage = @"发送参数错误";
            break;
        }
        case EQQAPIQQNOTINSTALLED:
        {
            errorMessage = @"未安装手Q";
            break;
        }
        case EQQAPIQQNOTSUPPORTAPI:
        {
            errorMessage = @"API接口不支持";
            break;
        }
        case EQQAPISENDFAILD:
        {
            errorMessage = @"发送失败";
            break;
        }
        case EQQAPIVERSIONNEEDUPDATE:
        {
            errorMessage = @"当前QQ版本太低，需要更新";
            break;
        }
        default:
        {
            break;
        }
    }
    if (errorMessage && [errorMessage isKindOfClass:[NSString class]] && errorMessage.length > 0) {
        [self showMessage:errorMessage];
    }
}
-(void)showMessage:(NSString*)message{
    [self.messageSubject sendNext:message];
}

/// 分享的类型数组 默认为微信、朋友圈
/// + 默认分享Icon数量: [A,B,C,D]  <== 初始化时设置
/// + 在默认分享Icon数量的数量上新增: [A,B,C,D,E,F]  <== shareTypesArrType = 1
/// +  重新设置分享Icon数量: [G,H,I,J]  <== shareTypesArrType = 2
/// + 清空所有分享Icon: []  <== array.count=0
-(void)shareIconsDataSource:(NSArray*)dataSource shareTypesArrType:(NSString*)type{
    // 默认
    [self.shareTypesArr addObject:@(SEGShareVCActionType_Share_WeChat)];
    [self.shareTypesArr addObject:@(SEGShareVCActionType_Share_FriendCircle)];
    
    if(dataSource && [dataSource isKindOfClass:[NSArray class]]){
        if (dataSource.count <= 0) {
            [self.shareTypesArr removeAllObjects];
            return;
        }
        if (type && [type isKindOfClass:[NSString class]] && [type isEqualToString:@"1"]) {
            [self.shareTypesArr addObjectsFromArray:dataSource];
        }else{
            [self.shareTypesArr removeAllObjects];
            [self.shareTypesArr addObjectsFromArray:dataSource];
        }
    }
}

/// 获取分享高清图的逻辑
-(void)shrareToWeChatOrQQWithType{
    if (self.shareImage) {
        return;
    }
    self.shareImage = [UIImage imageWithContentsOfFile:SEGPicName(@"AppIcon60")];
    
    if (!(self.shareImageUrlString &&
          [self.shareImageUrlString isKindOfClass:[NSString class]] &&
          [self.shareImageUrlString length] > 0)) {
        return;
    }
    
    if (!(self.shareImageUrlString && self.shareImageUrlString.length > 0)) {
        return;
    }
    
    NSURL *imageUrl = [NSURL URLWithString:self.shareImageUrlString];
    if (!imageUrl) {
        return;
    }
    
    [[[UIImageView alloc] init] setImageWithURL:imageUrl completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        if (image) {
            self.shareImage = image;
        }
    }];
}


/// 点击分享按钮触发的事件
/// @param tag 按钮下标
/// @param cardImage 分享图片时的高清图
-(void)segClickSharedChannelButton:(NSInteger)tag cardImage:(UIImage*)cardImage{
    [self shrareToWeChatOrQQWithType];
    
    NSInteger actionType = tag;
    [self segAnalyticsShareEventWithActionType:actionType objID:self.objID objName:self.objName objSection:self.objSection shareVCType:self.shareVCType];
    [self segHandleIntegralCodeWithActionType:actionType];
    
    //邀请邻居的分享链接需要添加分享渠道参数
    if (self.shareVCType == SEGShareVCType_Invite) {
        if (!self.inviteUrlString) {//第一次邀请链接为空 赋值 以后不变
            self.inviteUrlString = self.shareUrlString;
        }
        if (!self.channel) {
            switch (actionType) {
                case SEGShareVCActionType_Share_WeChat: //微信
                case SEGShareVCActionType_MiniProgram_WeChat:
                    self.channel = @"10";
                    break;
                case SEGShareVCActionType_Share_FriendCircle: //朋友圈
                    self.channel = @"20";
                    break;
                case SEGShareVCActionType_Share_QQ: //QQ
                    self.channel = @"30";
                    break;
                default:
                    break;
            }
            self.shareUrlString = [NSString stringWithFormat:@"%@&channel=%@",self.inviteUrlString,self.channel];
        }
        [self.sharedButtonClickSubject sendNext:@{@"type":@"1"}];
    }
    
    UIImage * hdImageTempt = self.hdImage ? self.hdImage : (cardImage ? cardImage : nil);
    switch (actionType) {
        case SEGShareVCActionType_Share_WeChat: //微信
        {
            [self segShareToWeChatWithScene:WXSceneSession ImageData:hdImageTempt ThumbImage:self.shareImage Title:self.shareTitle Description:self.shareText WebpageUrl:self.shareUrlString];
            
            break;
        }
        case SEGShareVCActionType_MiniProgram_WeChat: //微信小程序
        {
            [self seg_shareToWeChatMiniProgramWithParams:self.miniapp];
            break;
        }
        case SEGShareVCActionType_Share_FriendCircle: //朋友圈
        {
            [self segShareToWeChatWithScene:WXSceneTimeline ImageData:hdImageTempt ThumbImage:self.shareImage Title:self.shareTitle Description:self.shareText WebpageUrl:self.shareUrlString];
            
            break;
        }
        case SEGShareVCActionType_Share_QQ: //QQ
        {
            [self segShareToQQWithImageData:hdImageTempt Title:self.shareTitle PreviewImageData:self.shareImage Description:self.shareText WebpageUrl:self.shareUrlString];
            break;
        }
        default:
        {
            [self.sharedButtonClickSubject sendNext:@{@"type":@"2",@"value":@(actionType)}];
        }
    }
}


/// 触发分享积分行为
/// @param actionType actionType
- (void)segHandleIntegralCodeWithActionType:(NSInteger)actionType {
    // 点击QQ 微信 微信朋友圈 触发积分行为
    if (actionType == SEGShareVCActionType_Share_QQ || actionType == SEGShareVCActionType_Share_WeChat || actionType == SEGShareVCActionType_Share_FriendCircle) {
        NSString *moudle = @"";
        NSString *businessID = @"";
        if (self.shareVCType == SEGShareVCType_Invite) {
            moudle = SEGIntegralModule.inviteNeighbor;
        } else if (self.shareVCType == SEGShareVCType_Topic) {
            moudle = SEGIntegralModule.topicDetail;
            businessID = self.objID;
        } else if (self.shareVCType == SEGShareVCType_Pictorial) {
            moudle = SEGIntegralModule.articleDetail;
            businessID = self.objID;
        } else if (self.shareVCType == SEGShareVCType_Market || self.shareVCType == SEGShareVCType_Help) {
            moudle = SEGIntegralModule.neighborhoodCircle;
        }
        
        if (moudle.length > 0) {
            // [5.0.0需求] 点击QQ微信了就算分享成功
            [[SEGAnalyseBehaviorManager sharedManager] requestIntegralGrowthWithCode:SEGIntegralCode.share module:moudle businessID:businessID finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            }];
        }
    }
}

/// 分享业务埋点
/// @param objSection 分享对象的板块 用于事件埋点
- (void)segAnalyticsShareEventWithActionType:(SEGShareVCActionType)actionType
                                       objID:(NSString*)objID
                                     objName:(NSString*)objName
                                  objSection:(NSString*)objSection
                                 shareVCType:(SEGShareVCType)shareVCType{
    NSString *channel;
    switch (actionType) {
        case SEGShareVCActionType_Share_WeChat: //微信
        case SEGShareVCActionType_MiniProgram_WeChat: //微信小程序
        {
            channel = @"1";
            break;
        }
        case SEGShareVCActionType_Share_FriendCircle: //朋友圈
        {
            channel = @"2";
            break;
        }
        case SEGShareVCActionType_Share_QQ: //QQ
        {
            channel = @"4";
            break;
        }
        default:
            return;//不统计
    }
    
    NSMutableArray *values = [NSMutableArray array];
    if(objID)[values addObject:objID];
    if(objName)[values addObject:objName];
    if(kAccountCommunityID)[values addObject:kAccountCommunityID];
    if(kAccountCommunityName)[values addObject:kAccountCommunityName];
    if(channel)[values addObject:channel];
}

#pragma mark - getter
-(RACSubject *)messageSubject{
    if (!_messageSubject) {
        _messageSubject = [RACSubject subject];
    }
    return _messageSubject;
}
-(RACSubject *)sharedButtonClickSubject{
    if (!_sharedButtonClickSubject) {
        _sharedButtonClickSubject = [RACSubject subject];
    }
    return _sharedButtonClickSubject;
}
-(NSMutableArray *)shareTypesArr{
    if (!_shareTypesArr) {
        _shareTypesArr = [NSMutableArray array];
    }
    return _shareTypesArr;
}
-(NSArray *)otherActionTypesArr{
    if (!_otherActionTypesArr) {
        _otherActionTypesArr = [NSArray array];
    }
    return _otherActionTypesArr;
}
- (SEGShareVCType)shareVCType
{
    if (!_shareVCType) {
        _shareVCType = SEGShareVCType_Default;
    }
    return _shareVCType;
}

- (NSString *)objID
{
    if (!_objID) {
        _objID = [NSString string];
    }
    return _objID;
}

- (NSString *)objSection
{
    if (!_objSection) {
        _objSection = [NSString string];
    }
    return _objSection;
}

- (NSString*)shareUrlString
{
    if (!_shareUrlString) {
        _shareUrlString = @"";
    }
    return _shareUrlString;
}

#pragma mark - setter

- (void)setShareTitle:(NSString *)shareTitle
{
    if (shareTitle) {
        if (shareTitle.length > 100) {
            _shareTitle = [shareTitle substringToIndex:100];
        }else {
            _shareTitle = shareTitle;
        }
    }else {
        _shareTitle = @"";
    }
}

- (void)setShareText:(NSString *)shareText
{
    if (shareText) {
        if (shareText.length > 100) {
            _shareText = [shareText substringToIndex:100];
        }else {
            _shareText = shareText;
        }
    }else {
        _shareText = @"";
    }
}


-(void)setShareImage:(UIImage *)shareImage{
    if (shareImage) {
        _shareImage = [SEGUtils scaleImage:shareImage maxSize:CGSizeMake(180, 160)];//微信分享限制大小为32K 这个比例为宽高比计算出的31K大小图片
    }
}

-(void)setShareImageUrlString:(NSString *)shareImageUrlString{
    _shareImageUrlString = shareImageUrlString;
    [self shrareToWeChatOrQQWithType];
}
@end
